const express = require('express');
const mongo = require('../db/mongo')
const router = express.Router();

//获取标签列表
router.get('/', async (req, res) => {
    var data = await mongo.find('tag')
    if (data) {
        res.send({
            code: 200,
            data,
            msg: '请求成功'
        })
    } else {
        res.send({
            code: 400,
            data: [],
            msg: '请求失败'
        })
    }
})

//增加标签
router.post('/add', async (req, res) => {
    const config = req.body;
    console.log(config);
    const data = await mongo.insert('tag', config);
    if (data) {
        res.send({
            code: 200,
            msg: '添加成功'
        })
    } else {
        res.send({
            code: 400,
            msg: '添加失败'
        })
    }
})




//删除标签

router.delete('/:id', async (req, res) => {
    const { id } = req.params;
    const { result, num } = await mongo.remove('tag', { _id: id });
    if (result && num == 0) {
        res.send({
            code: 300,
            msg: `未找到此标签`
        })
    } else if (result) {
        res.send({
            code: 200,
            msg: `成功删除${num}个标签`
        })
    }
    else {
        res.send({
            code: 400,
            msg: '删除失败'
        })
    }
})

//修改标签
router.put('/:id', async (req, res) => {
    const { id } = req.params;
    const { lable, describe } = req.body;

    const result = await mongo.updata('tag', { _id: id }, {
        $set: {
            lable,
            describe
        }
    });
    if (result) {
        res.send({
            code: 200,
            msg: '修改成功'
        })
    } else {
        res.send({
            code: 400,
            msg: '修改失败'
        })
    }
})




module.exports = router